package com.pms.web;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.result.JsonResult;
import com.pms.result.ResultCode;
import com.pms.service.*;
import com.pms.util.SmSUtile;
import com.pms.util.WebUtil;
import com.pms.util.idutil.SnowFlake;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
 *  前端控制器
 * @author zyl
 * @since 2017-07-06
 */
@RestController
@RequestMapping("user")
@Api(value = "后台用户管理",description = "后台用户管理")
public class BaseUserController extends BaseController {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IBaseUserService baseUserService;
    @Autowired
    IBaseMenuService baseMenuService;
    @Autowired
    com.pms.cache.utils.RedisCacheUtil RedisCacheUtil;
    @Autowired
    ICompanyCodeService companyCodeService;
    @Autowired
    IBaseGroupService baseGroupService;
    /**
     * 修改密码
     * @param id
     * @param password
     * @return
     */
    @PostMapping("/userPassword/{id}")
    @ApiOperation(value = "修改密码", notes = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "oldPassword", value = "旧密码", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "password", value = "新密码", paramType = "form", dataType = "String"),
    })
    public R userPassword(@PathVariable String id, String password,String oldPassword){
        parameterIsNull(id,"用户ID不存在");
        parameterIsNull(password,"新密码不能为空");
        parameterIsNull(oldPassword,"旧密码不能为空");
        BaseUser baseUser =  baseUserService.selectByPerssId(Long.parseLong(id));
        parameterIsNull(baseUser,"该用户信息不存在");
        if(baseUser.getPassword().equals(BCrypt.hashpw(oldPassword,baseUser.getPassword()))){
            baseUser.setPassword(BCrypt.hashpw(password,baseUser.getPassword()));
            baseUser.setUpdTime(new Date());
            baseUser.setUpdName(baseUser.getName());
            baseUserService.updateById(baseUser);
            return R.ok();
        }else{
            return R.error(400,"原密码不正确，请从新输入");
        }

    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.DELETE)
    public R update(@PathVariable Long id){
        baseUserService.deleteById (id);
        return R.ok();
    }

    /**
     * 查询我的用户信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public R findById(@PathVariable Long id){
        parameterIsNull(id,"ID不能为空");
        BaseUser user =baseUserService.selectByPerssId(id);
        parameterIsNull(user,"用户信息不存在");
        user.setPassword(null);
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("user",user);
        return R.ok().put("data",map).putDescription(BaseUser.class);
    }

    /**
     * 查询所有
     * @return
     */
    @RequestMapping(value = "/all",method = RequestMethod.GET)
    public List<BaseUser> all(){
        return baseUserService.selectList(null);
    }

    /**
     * 分页查询用户信息
     * @param limit
     * @param page
     * @param name
     * @param userId
     * @return
     */
    @RequestMapping(value = "/page",method = RequestMethod.GET)
    public R page(@RequestParam  int limit, @RequestParam int page, String name,Long userId){
        parameterIsNull(userId,"用户ID不能为空");
        BaseUser user=baseUserService.selectById_User(userId);
        parameterIsNull(user,"用户信息不存在");
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        Page<Map<String,Object>> pages = new Page<>(page,limit);
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("companyCode",user.getCompanyCode());
        if (StringUtils.isNotBlank(name)){
            parameter.put("name","and (u.username like binary '%"+name+"%' or g.name like binary '%"+name+"%'" +
                    "or u.crt_user like binary '%"+name+"%'or u.crt_name like binary '%"+name+"%'or u.crt_time like binary '%"+name+"%')");
        }
        parameter.put("limit",limit);
        parameter.put("page",(page-1)*limit);
        pages = baseUserService.selectPageList(pages,parameter);
        return R.ok().put("data",pages);
    }
    /**
     * 当前用户
     * @return
     */
    @ApiOperation(value = "当前用户信息")
    @RequestMapping(value = "/current")
    public JsonResult current() {
        logger.info("-------------->>> 当前用户信息");
        String userName = getCurrentUserName();
        BaseUser sysUser = baseUserService.getUserByUsername(userName,null);
        if (sysUser != null) {
            sysUser.setPassword(null);
        }
        Long userId = baseUserService.getUserByUsername(getCurrentUserName(),null).getId();
        List<BaseMenu> menuList = baseMenuService.getUserAuthorityMenuByUserId(userId.intValue());
        Map map = new HashMap();
        map.put("menus",menuList);
        map.put("user",sysUser);
        logger.info(new JsonResult(ResultCode.SUCCESS,"操作成功！",map).toString());
        return new JsonResult(ResultCode.SUCCESS,"操作成功！",map);
    }




    /**
     * 修改状态
     * @param id
     * @param status
     * @return
     */
    @PostMapping("/updateStatus/{id}")
    @ApiOperation(value = "修改状态", notes = "修改状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态1.启用2.禁用  ", paramType = "form", dataType = "String"),
    })
    public R updateStatus(@PathVariable String id, Integer status){
        parameterIsNull(id,"用户ID不存在");
        parameterIsNull(status,"用户状态不能为空");
        BaseUser baseUser =  baseUserService.selectByPerssId(Long.parseLong(id));
        parameterIsNull(baseUser,"该用户信息不存在");
        baseUser.setStatus(status);
        baseUser.setUpdTime(new Date());
        baseUser.setUpdName(baseUser.getName());
        baseUserService.updateById(baseUser);
        return R.ok();
    }

    /**
     * 发送验证码(阿里云短信）
     * @param request
     * @param phone
     * @param type
     * @param companyCode
     * @return
     */
    @ApiOperation(value = "发送验证码(阿里云短信)")
    @PostMapping(value="/aliyun/smsCode")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "companyCode", value = "公司编码", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "type", value = "验证类型(1.用户注册2.身份验证3.修改密码4.身份变更5.登录异常6.快速注册7.修改支付密码)", required = true, dataType = "String", paramType = "form"),
    })
    public R aliyunGetSmsCode(HttpServletRequest request, String phone, String type,String companyCode){
        parameterIsBlank(phone,"手机号码不能为空");
        parameterIsBlank(companyCode,"公司编码不能为空");
        parameterIsBlank(type,"验证类型不能为空");
        boolean isphone= WebUtil.isMobileNO(phone.trim());//手机号正则验证
        if(isphone == false){ return R.error("手机号码格式不正确，请你从新输入！");}
        BaseUser user;
        if (type.equals("1")){//注册
            user=baseUserService.selectOne(new EntityWrapper<BaseUser>().eq("mobile_phone",phone).and().eq("company_code",companyCode));
            if (user!=null){
                throw  new RRException("该账号已被注册，请重新输入账号！",400);
            }
        }else{
            user=baseUserService.selectOne(new EntityWrapper<BaseUser>().eq("mobile_phone",phone).and().eq("company_code",companyCode));
            parameterIsNull(user,"该账号尚未被注册，请重新输入账号");
        }
        String   smsCode = SmSUtile.sendSms(phone, Integer.parseInt(type), null);
        if (smsCode.equals("error")){ return R.error("对不起！该手机号一分钟不能超过一条，请稍等一分钟后再试！");}
        if (StringUtils.isNotBlank(smsCode)) {
            if (Integer.valueOf(smsCode) <= 0) {
                smsCode = "0";
            }
            RedisCacheUtil.saveAndUpdate(phone + "PMS_RegisterSMSCode",smsCode,10);
            return R.ok().put("codes",smsCode);
        } else {
            smsCode = "0";
        }
        return R.ok();
    }

    /**
     * 验证码匹对
     * @param phone
     * @param code
     * @return
     */
    @PostMapping("/Verification")
    @ApiOperation(value = "验证码匹对", notes = "验证码匹对")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "code", value = "验证码", paramType = "form", dataType = "String"),
    })
    public R Verification(String phone, String code) {
        Assert.isBlank(code, "验证码不能为空");
        parameterIsBlank(phone,"手机号码不能为空");
        boolean isphone= WebUtil.isMobileNO(phone.trim());//手机号正则验证
        if(isphone == false){ return R.error("手机号码格式不正确，请从新输入！");}
        Object SMSCode= RedisCacheUtil.getVlue(phone + "PMS_RegisterSMSCode");
        if(SMSCode==null){ return R.error("输入验证码已失效！"); }
        if (code != null && code.equals(SMSCode.toString())) {
            RedisCacheUtil.clearByKey(phone + "PMS_RegisterSMSCode");
            return R.ok();
        }else{
            return R.error("输入验证码不正确！");
        }
    }

    /**
     * 修改找回密码
     * @param phone
     * @param passWord
     * @param companyCode
     * @return
     */
    @PostMapping("/retrievePassword")
    @ApiOperation(value = "修改找回密码", notes = "修改找回密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "passWord", value = "密码", paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "companyCode", value = "公司编码", required = true, dataType = "String", paramType = "form")
    })
    public R retrievePassword(String phone, String passWord,String companyCode) {
        Assert.isBlank(phone, "手机号不能为空");
        Assert.isBlank(passWord, "密码不能为空");
        parameterIsBlank(companyCode,"公司编码不能为空");
        boolean isphone= WebUtil.isMobileNO(phone.trim());//手机号正则验证
        if(isphone == false){ return R.error("手机号码格式不正确，请你从新输入！");}
        BaseUser user=baseUserService.selectbyCompanyCode(phone,companyCode);
        parameterIsNull(user,"该账号尚未被注册，请重新输入手机号");
        user.setPassword(BCrypt.hashpw(passWord,user.getPassword()));
        baseUserService.updateById(user);
        return R.ok();
    }

    /**
     * 添加用户信息
     * @param entity
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("添加用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name="username",value="账号",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="password",value="密码",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="name",value="昵称",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="mobilePhone",value="电话",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="email",value="邮箱",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="description",value="备份",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="userId",value="当前登录用户ID",required = true,dataType = "String",paramType="form"),
    })
    public R add(BaseUser entity,Long userId){
        parameterIsNull(entity.getUsername(),"请填写账号信息");
        parameterIsNull(entity.getPassword(),"请输入密码");
        parameterIsNull(entity.getMobilePhone(),"请输入手机号");
        parameterIsNull(entity.getEmail(),"请输入邮编");
        BaseUser users = baseUserService.selectById(userId);
        if (users==null){throw  new RRException("请登录！",400); }
        CompanyCode  code=companyCodeService.selectOne(new EntityWrapper<CompanyCode>().eq("company_code",users.getCompanyCode()));
        parameterIsNull(code,"该系统信息不存在");
        boolean isphone= WebUtil.isMobileNO(entity.getMobilePhone().trim());//手机号正则验证
        if(isphone == false){ return R.error("手机号码格式不正确，请你从新输入！");}
        BaseUser user =baseUserService.selectOne(new EntityWrapper<BaseUser>().eq("company_code",code.getCompanyCode()).and().eq("username",entity.getUsername()));
        if (user!=null){throw  new RRException("已有相同账号信息存在，请重新输入",400);}
        BaseUser mobilePhone=  baseUserService.selectOne(new EntityWrapper<BaseUser>().eq("company_code",code.getCompanyCode()).and().eq("mobile_phone",entity.getMobilePhone()));
        if (mobilePhone !=null){throw  new RRException("已有相同手机号存在，请重新输入",400); }
        int emails=  baseUserService.selectCount(new EntityWrapper<BaseUser>().eq("company_code",code.getCompanyCode()).and().eq("email",entity.getEmail()));
        if (emails != 0){throw  new RRException("已有相同邮箱存在，请重新输入",400); }
        Long userIds= BaseModel.returnStaticIdLong();;
        entity.setId(userIds);//ID
        entity.setCompanyCode(code.getCompanyCode());//公司编码
        entity.setPassword(BCrypt.hashpw(entity.getPassword(),"$2a$12$S/yLlj9kzi5Dgsz97H4rAe9RZTx2QMcnckioqofjv8tYtoQKET/YG"));
        entity.setUsername(entity.getUsername().trim());//账号
        entity.setType(entity.getType());//类型
        entity.setName(entity.getName().trim());//昵称q
        entity.setEmail(entity.getEmail().trim());
        entity.setCrtTime(new Date());
        entity.setType(2);
        entity.setDeletedState(1);
        entity.setImg("http://upimg.ahmkj.cn/pms/img82389271.jpg");
        entity.setCrtUser(getCurrentUserMap().get("userName"));
        entity.setCrtName(users.getName());
        entity.setStatus(1);//默认启动
        entity.setSex(3);
        entity.setDescription(entity.getDescription());
        baseUserService.insert(entity);
        return R.ok();
    }
    /**
     * 修改用户信息
     * @param id
     * @param mobilePhone
     * @param email
     * @param description
     * @return
     */
    @PostMapping(value = "/update")
    @ApiOperation("修改用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="用户ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="password",value="密码",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="mobilePhone",value="电话",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="email",value="邮箱",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="name",value="昵称",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="description",value="备份",required = false,dataType = "String",paramType="form"),
    })
    public R update(Long id,String mobilePhone,String email,String description,String password,String name){
        parameterIsNull(id,"请填写用户ID");
        BaseUser user= baseUserService.selectById(id);
        if (user==null){throw  new RRException("账号信息不存在，请重新输入",400); }
        if (StringUtils.isNotBlank(mobilePhone)){
            if(!mobilePhone.equals(user.getMobilePhone())){
                boolean isphone= WebUtil.isMobileNO(mobilePhone.trim());//手机号正则验证
                if(isphone == false){ return R.error("手机号码格式不正确，请你从新输入！");}
                BaseUser users=  baseUserService.selectOne(new EntityWrapper<BaseUser>().eq("company_code",user.getCompanyCode()).and().eq("mobile_phone",mobilePhone));
                if (users !=null){throw  new RRException("已有相同手机号存在，请重新输入",400); }

                user.setMobilePhone(mobilePhone);}
            }
        if (StringUtils.isNotBlank(description)){
            user.setDescription(description);}
        if (StringUtils.isNotBlank(name)){
            user.setName(name);}
        if (StringUtils.isNotBlank(email)){
            if(!email.equals(user.getEmail())){
                int emails=  baseUserService.selectCount(new EntityWrapper<BaseUser>().eq("email",email).and().eq("company_code",user.getCompanyCode()));
                if (emails != 0){throw  new RRException("已有相同邮箱存在，请重新输入",400); }
                user.setEmail(email);
            }
        }
            user.setUpdTime(new Date());
        if (StringUtils.isNotBlank(password)){
            user.setPassword(BCrypt.hashpw(password,user.getPassword()));
        }
        user.setUpdName(getCurrentUserMap().get("userName"));
        baseUserService.updateById(user);
        return R.ok();
    }


    /**
     * 查询权限信息模块
     * @return
     */
    @GetMapping(value = "/selectGroupList")
    @ApiOperation("查询权限信息模块")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "userId", paramType = "form"),
    })
    public R selectGroupList(Long userId){
        parameterIsNull(userId,"用户ID不能为空");
        BaseUser user =baseUserService.selectOne(new EntityWrapper<BaseUser>().eq("id",userId));
        if (user==null){return  R.error(400,"用户信息不存在");}
        Integer groupType=null;
        if (user.getType()==1){
            groupType=1;
        }else if (user.getType()==2){
            groupType=2;
        }
       List<BaseGroup>  list= baseGroupService.selectGroupList(user.getCompanyCode(),groupType);
        return  R.ok().put("data",list);
    }


    /**
     * 删除用户
     * @param id
     * @return
     */
    @PostMapping("/deleteById")
    @ApiOperation(value = "删除用户", notes = "删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", paramType = "form", dataType = "String"),
    })
    public R deleteById(String id){
        parameterIsNull(id,"用户ID不存在");
        BaseUser baseUser =  baseUserService.selectByPerssId(Long.parseLong(id));
        parameterIsNull(baseUser,"该用户信息不存在");
        baseUser.setDeletedState(2);//改成已删除
        baseUserService.updateById(baseUser);
        return R.ok();
    }



}

